package com.bishe.controller;


import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bishe.config.DataException;
import com.bishe.entity.*;
import com.bishe.entity.response.R;
import com.bishe.service.*;
import com.bishe.util.BeansUtil;
import com.bishe.util.HttpRequestUtils;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Serializable;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * (WzOut)表控制层
 *
 * @author makejava
 * @since 2024-03-04 00:02:38
 */
@CrossOrigin
@RestController
@RequestMapping("wzout")
public class WzOutController {
    /**
     * 服务对象
     */
    @Resource
    private WzOutService WzOutService;

    @Resource
    private FileService fileService;

    @Resource
    private WzTypeService wzTypeService;

    @Resource
    private WarehouseService warehouseService;

    @Resource
    private UserService userService;

    @Resource
    private WzInfoService wzInfoService;

    @ApiOperation("导出信息")
    @GetMapping("/output/{type}")
    public void download(HttpServletResponse response, @PathVariable Integer type) {
        List<DownloadData> dataList = null;

        if (1==type){
            List<WzOut> wzOuts = WzOutService.list();
            dataList = BeansUtil.listCopy(wzOuts, DownloadData.class);
        }else {
            List<WzInfo> wzInfos = wzInfoService.list();
            dataList = BeansUtil.listCopy(wzInfos, DownloadData.class);

        }
        if (CollUtil.isEmpty(dataList)){
            return;
        }

        OutputStream out = null;
        try (ExcelWriter writer = ExcelUtil.getWriter()) {
            writer.addHeaderAlias("name", "物资名");
            writer.addHeaderAlias("weight", "重量");
            writer.addHeaderAlias("type", "物资类别");
            writer.addHeaderAlias("wzNum", "物资数量");
            writer.addHeaderAlias("wzCkNum", "物资出库数量");
            writer.addHeaderAlias("wzRemaining", "物资剩余数量");
            writer.write(dataList, true);// 写入数据
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("数据.xlsx", "UTF-8"));
            out = response.getOutputStream();// 获取流
            writer.flush(out, true); // 将数据流输出到文件
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            IoUtil.close(out);// 流的操作要关闭

        }
    }


    @GetMapping("/getWzList/{type}")
    @ApiOperation("出/入库记录 1 出 2入")
    public R getWzList(@PathVariable Integer type) {
        if (type == 1) {
            List<WzOut> list = WzOutService.list();
            return R.ok(list);
        }
        List<WzInfo> list = wzInfoService.list(Wrappers.lambdaQuery(WzInfo.class).eq(WzInfo::getStatus, 1));
        return R.ok(list);
    }


    @GetMapping("/updateStatus/{id}/{status}")
    @ApiOperation("根据状态删除")
    public R updateStatus(@PathVariable String id, @PathVariable Integer status) {

        WzOut byId = WzOutService.getById(id);
        if (byId == null) {
            return R.ok("没有这条数据");
        }
        switch (status) {
            case 1:
                WzInfo wzInfo = wzInfoService.getById(byId.getUid());
                if (wzInfo != null) {
                    boolean update = wzInfoService.update(Wrappers.lambdaUpdate(WzInfo.class)
                            .set(WzInfo::getWzRemaining, wzInfo.getWzRemaining() + byId.getWzCkNum())
                            .set(WzInfo::getWzCkNum, wzInfo.getWzCkNum() - byId.getWzCkNum())
                    );

                    if (update) {
                        WzOutService.removeById(id);
                    }

                }
                break;
            case 2:
                byId.setStatus(1);
                byId.setOrderNo(null);
                byId.setPhone(null);
                byId.setPosition(null);
                byId.setTakeDeliveryInfo(null);
                byId.setSjr(null);
                byId.setExpressman(null);
                byId.setYjsj(null);
                WzOut out = new WzOut();
                BeanUtil.copyProperties(byId, out);
                WzOutService.removeById(byId.getId());
                WzOutService.save(out);
                break;
            case 3:
                byId.setStatus(1);
                byId.setOrderNo(null);
                byId.setPhone(null);
                byId.setPosition(null);
                byId.setTakeDeliveryInfo(null);
                byId.setSjr(null);
                byId.setExpressman(null);
                byId.setYjsj(null);
                WzOut out2 = new WzOut();
                BeanUtil.copyProperties(byId, out2);
                WzOutService.removeById(byId.getId());
                WzOutService.save(out2);
                break;
            case 4:
                WzOutService.removeById(id);
                break;

            default:
                return R.ok("没有这个状态");
        }


        return R.ok(null);
    }


    /**
     * 分页查询所有数据
     *
     * @param page  分页对象
     * @param WzOut 查询实体
     * @return 所有数据
     */
    @GetMapping("/toPage")
    @ApiOperation("分页查询所有数据")
    public R selectAll(Page<WzOut> page, WzOut WzOut) {
        LambdaQueryWrapper<WzOut> WzOutLambdaQueryWrapper = new LambdaQueryWrapper<>(WzOut);

        List<FileInfo> list = fileService.list();
        Map<String, List<FileInfo>> fileMap = list.stream().collect(Collectors.groupingBy(FileInfo::getId));
        List<WzType> wzTypeList = wzTypeService.list();
        Map<String, String> wzTypeMap = wzTypeList.stream().collect(Collectors.toMap(WzType::getId, WzType::getName));

        Page<WzOut> WzOutPage = WzOutService.page(page, WzOutLambdaQueryWrapper);

        for (WzOut WzOut1 : WzOutPage.getRecords()) {
            User user = userService.getById(WzOut1.getCreateBy());
            if (ObjectUtil.isNotNull(user)) {
                WzOut1.setCreateName(user.getUserName());
            }

            WzInfo wzInfo = wzInfoService.getById(WzOut1.getUid());
            Warehouse byId = null;
            if (ObjectUtil.isNotNull(wzInfo)) {
                byId = warehouseService.getById(wzInfo.getUid());
            }
            if (ObjectUtil.isNotNull(byId)) {
                WzOut1.setWarehouseName(byId.getName());
            }

            List<FileInfo> fileInfos = fileMap.get(WzOut1.getDataId());
            if (CollUtil.isNotEmpty(fileInfos)) {
                WzOut1.setFileInfo(fileInfos.get(0));
            }

            String typeName = wzTypeMap.get(WzOut1.getUid());
            if (StrUtil.isNotEmpty(typeName)) {
                WzOut1.setType(typeName);
            }
        }

        return R.ok(WzOutPage);
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("{id}")
    @ApiOperation("通过主键查询单条数据")
    public R selectOne(@PathVariable Serializable id) {
        return R.ok(this.WzOutService.getById(id));
    }

    /**
     * 新增数据
     *
     * @param WzOut 实体对象
     * @return 新增结果
     */
    @PostMapping
    @ApiOperation("新增数据")
    public R insert(@RequestBody WzOut WzOut) {
        if (WzOut.getWzNum() - WzOut.getWzCkNum() < 0) {
            throw new DataException("出库数量不能大于库存数量");
        }
        WzInfo wzInfo = wzInfoService.getById(WzOut.getUid());
        WzOut.setWzRemaining(wzInfo.getWzRemaining() - WzOut.getWzCkNum());
        WzOut.setCreateBy(StpUtil.getLoginIdAsString());
        return R.ok(this.WzOutService.save(WzOut));
    }

    /**
     * 修改数据
     *
     * @param WzOut 实体对象
     * @return 修改结果
     */
    @PutMapping
    @ApiOperation("修改数据")
    public R update(@RequestBody WzOut WzOut) {
        return R.ok(this.WzOutService.updateById(WzOut));
    }

    /**
     * 删除数据
     *
     * @param idList 主键结合
     * @return 删除结果
     */
    @DeleteMapping
    @ApiOperation("删除数据")
    public R delete(@RequestParam("idList") List<Long> idList) {
        return R.ok(this.WzOutService.removeByIds(idList));
    }
}

